import request from "@/utils/request";
import type { AxiosPromise } from "axios";
import type {
  CaptchaResult,
  LoginData,
  LoginResult,
  UserInfo,
  RolesPerms,
  LoginQrcodeCreate,
  LoginQrcodeResp,
  LoginQrcodeReq,
  MyOrganList,
  SendValidCodeReq,
  RegisterReq,
  ForgotPhoneEmailReq,
} from "./types";
import { useUserStore } from "@/stores/modules/user";
import { vueMetaEnv } from "@/settings";
import { da } from "element-plus/es/locales.mjs";

/**
 * 登录API
 *
 * @param data {LoginData}
 * @returns
 */
export function loginApi(data: LoginData): AxiosPromise<LoginResult> {
  const formData = new FormData();
  formData.append("tenant", useUserStore().user.tenant);
  formData.append("directoryId", vueMetaEnv.APP_DIRECTORY_ID as string);
  formData.append("userName", data.username);
  formData.append("encodePwd", data.password);
  formData.append("scope", data.scope as string);
  formData.append("clientId", vueMetaEnv.APP_CLIENT_ID);
  formData.append("captchaId", data.captchaKey as string);
  formData.append("captchaCode", data.captchaCode as string);
  return request({
    url: "/v1/rbac/auth/login",
    method: "post",
    data: formData,
    headers: {
      Authorization: false,
    },
  });
}

/**
 * 手机号邮箱注册登录
 * @param token
 * @returns
 */
export function registerApi(data: RegisterReq): AxiosPromise<LoginResult> {
  data.tenant = useUserStore().user.tenant;
  data.directoryId = vueMetaEnv.APP_DIRECTORY_ID as string;
  data.clientId = vueMetaEnv.APP_CLIENT_ID;
  return request({
    url: "/v1/rbac/register/phone_email",
    method: "post",
    data: data,
  });
}
/**
 * 刷新Token
 */
export function refreshTokenApi(token: string): AxiosPromise<LoginResult> {
  const formData = new FormData();
  formData.append("tenant", useUserStore().user.tenant);
  formData.append("refreshToken", token);
  formData.append("clientId", vueMetaEnv.APP_CLIENT_ID);
  return request({
    url: "/v1/rbac/auth/refresh_token",
    method: "post",
    data: formData,
  });
}

/**
 * 注销API
 */
export function logoutApi(accessToken: string) {
  return request({
    url:
      "/v1/rbac/auth/logout?tenant=" +
      useUserStore().user.tenant +
      "&client_id=" +
      vueMetaEnv.APP_CLIENT_ID +
      "&accessToken=" +
      accessToken,
    method: "delete",
  });
}

/**
 * 获取验证码
 */
export function getCaptchaApi(): AxiosPromise<CaptchaResult> {
  return request({
    url: "/v1/captcha/classic",
    method: "get",
  });
}

/**
 * 获取手机号验证码
 */

export function sendcode(data: SendValidCodeReq): AxiosPromise<CaptchaResult> {
  return request({
    url: "/v1/rbac/auth/sendcode",
    method: "post",
    data: data,
  });
}

/**
 * 通过验证码登录
 */
export function logincode(data: any): AxiosPromise<CaptchaResult> {
  return request({
    url: "/v1/rbac/auth/logincode",
    method: "post",
    data: data,
  });
}

/**
 * 用户信息
 */
export function getUserInfoApi(): AxiosPromise<UserInfo> {
  return request({
    url: "/v1/rbac/auth/user?tenant=" + useUserStore().user.tenant,
    method: "get",
  });
}

// 修改个人用户
export function updateUser(data: any) {
  return request({
    url: "/v1/rbac/auth/user",
    method: "patch",
    data: data,
  });
}

// 修改个人密码
export function updatePwd(encodeOldPwd: string, encodeNewPwd: string) {
  const data = {
    tenant: useUserStore().user.tenant,
    encodeOldPwd: encodeOldPwd,
    encodeNewPwd: encodeNewPwd,
  };
  return request({
    url: "/v1/rbac/auth/change_pwd",
    method: "patch",
    data: data,
  });
}

// 用户身份列表
export function allowRunAsUser() {
  return request({
    url: "/v1/rbac/auth/allow_run_as_user?tenant=" + useUserStore().user.tenant,
    method: "get",
  });
}

/**
 * 切换用户身份
 */
export function runAsUser(userId: string) {
  const data = {
    tenant: useUserStore().user.tenant,
    userId: userId,
  };
  return request({
    url: "/v1/rbac/auth/run_as",
    method: "post",
    data: data,
  });
}

/*
 * 登录选择动态互斥角色,无需权限.
 */
export function selectDsdRoles() {
  return request({
    url: "/v1/rbac/auth/select_dsd_roles?tenant=" + useUserStore().user.tenant,
    method: "get",
  });
}

/**
 * 获取所有角色列表
 *
 * @returns 返回请求响应结果
 */
export function listRoles(): AxiosPromise<RolesPerms> {
  return request({
    url: "/v1/rbac/auth/roles_perms?tenant=" + useUserStore().user.tenant,
    method: "get",
  });
}

/**
 * 获取所有路由列表
 *
 * @returns 返回请求结果的Promise对象
 */
export function listRoutes() {
  return request({
    url: "/v1/rbac/auth/menus?tenant=" + useUserStore().user.tenant,
    method: "get",
  });
}

/**
 * 获取部门树形列表
 *
 * @param deptId 部门ID，可选
 * @returns 返回部门树形列表
 */
export function treelistDept(deptId?: string) {
  const query = {
    tenant: useUserStore().user.tenant,
    excludeId: deptId,
  };
  return request({
    url: "/v1/rbac/dept/treelist",
    method: "get",
    params: query,
  });
}

/**
 * 获取树形列表中所有岗位信息
 *
 * @returns 返回请求结果
 */
export function treelistJob() {
  const query = {
    tenant: useUserStore().user.tenant,
    roleType: "job",
    hasRoleType: true,
  };
  return request({
    url: "/v1/rbac/role/treelist",
    method: "get",
    params: query,
  });
}

//获取登录二维码
export function createLoginQrcode(): AxiosPromise<LoginQrcodeResp> {
  const data = {
    tenant: useUserStore().user.tenant,
    authorizerAppid: vueMetaEnv.APP_WECHAT_APPID,
  } as LoginQrcodeCreate;
  return request({
    url: "/v1/wechat/auth/login_qrcode",
    method: "post",
    data: data,
  });
}

//扫码登录检查
export function loginQrcode(data: LoginQrcodeReq): AxiosPromise<LoginResult> {
  const formData = new FormData();
  formData.append("tenant", useUserStore().user.tenant);
  formData.append("directoryId", vueMetaEnv.APP_DIRECTORY_ID as string);
  formData.append("ticket", data.ticket);
  formData.append("authorizerAppid", vueMetaEnv.APP_WECHAT_APPID as string);
  formData.append("scope", data.scope as string);
  formData.append("clientId", vueMetaEnv.APP_CLIENT_ID);
  return request({
    url: "/v1/rbac/auth/login_qrcode",
    method: "post",
    data: formData,
    headers: {
      Authorization: false,
    },
  });
}

// 登录组织，用户Token换组织用户Token，参数：组织token值 organID@e01.
export function loginOrganApi(data: string): AxiosPromise<LoginResult> {
  return request({
    url: "/v1/rbac/login_organ",
    method: "post",
    data: data,
  });
}

// 查询我的组织列表信息
export function myorganList(): AxiosPromise<MyOrganList> {
  return request({
    url: "/v1/vcard_core/myorgan/list/" + useUserStore().user.tenant,
    method: "get",
  });
}

// 忘记密码/找回密码/重置密码.
export function forgotPhoneEmail(
  data: ForgotPhoneEmailReq,
): AxiosPromise<boolean> {
  data.directoryId = vueMetaEnv.APP_DIRECTORY_ID as string;
  data.clientId = vueMetaEnv.APP_CLIENT_ID;
  data.tenant = useUserStore().user.tenant;
  return request({
    url: "/v1/rbac/forgot/phone_email",
    method: "post",
    data: data,
  });
}
